package com.example.content.viewmodule.search

import com.example.content.DO_ACTION
import com.example.content.SEARCH_PAGE_PRODUCT
import com.example.content.SEARCH_PAGE_USER
import com.example.content.manager.GlobalMgr
import com.example.content.repository.RepositoryMgr
import com.example.content.repository.bean.*
import com.example.content.viewmodule.BaseViewModel
import com.example.content.viewmodule.viewdata.CommonViewState
import com.example.core.livedata.SingleLiveEvent

/**
 * Created by zhudongao
 * Desc
 * Date 2020/11/29
 */
class SearchViewModel: BaseViewModel<CommonViewState>() {

    val searchKeys = SingleLiveEvent<List<String>>()
    val productResult = SingleLiveEvent<List<ProductInfo>>()
    val userResult = SingleLiveEvent<List<UserInfo>>()

    fun search(key: String, type:Int) {
        launch(
            block = {
                val searchReq = SearchReq(key = key, type = type)
                when (type) {
                    SEARCH_PAGE_PRODUCT -> {
                        productResult.postValue(RepositoryMgr.searchProduct(searchReq).apiData())
                    }
                    SEARCH_PAGE_USER -> {
                        userResult.postValue(RepositoryMgr.searchUser(searchReq).apiData())
                    }
                }
            }
        )
    }

    fun getSearchKey(key: String) {
        launch(
            block = {
                searchKeys.postValue(RepositoryMgr.getSearchKey(key).apiData())
            }
        )
    }

    /**
     * 关注、取消关注
     */
    fun follow(followReq: FollowReq) {
        launch(
            block = {
                val result = RepositoryMgr.follow(followReq)
                GlobalMgr.follow.postValue(result.apiData())
            }
        )
    }

    /**
     * 点赞, 收藏
     */
    fun userAction(userActionReq: UserActionReq) {
        launch(
            block = {
                val result = RepositoryMgr.userAction(userActionReq)
                if (result.code == 200) {
                    GlobalMgr.collect.postValue(Triple(userActionReq.creation_id, userActionReq.action_type == DO_ACTION, System.currentTimeMillis()))
                    GlobalMgr.thumbUp.postValue(true)
                }
            }
        )
    }
}